package com.runrunfast.fxj.utils;


import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.util.StringUtils;

/**
 *  json 工具类
 * @author: 陈胤训
 * @create: 2018-12-05 18:32
 **/
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        //config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }

    public static <T> String obj2String(T src){
        if (StringUtils.isEmpty(src)){
            return null;
        }
        try{
            return  src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e){
            log.warn("将对象解析为字符串异常 error:{}", e);
            return null;
        }
    }

    public static <T> T string2Obj(String src , TypeReference<T> tTypeReference){
        if (src == null || tTypeReference == null) {
            return null;
        }
        try {
            return (T) (tTypeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, tTypeReference));
        } catch (Exception e) {
            log.warn("将字符串解析为对象异常, String:{}, TypeReference<T>:{}, error:{}", src, tTypeReference.getType(), e);
            return null;
        }

    }
}
